/*
This file is part of IRCaBot.
IRCaBot is IRC logger with features.
Source code: https://notabug.org/acetone/ircabot.
Copyright (C) acetone, 2023.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "httpserversocket.h"
#include "httpserver.h"
#include "config.h"

#include <QDebug>
#include <QThread>
#include <QApplication>

HttpServer::HttpServer(QObject *parent) : QTcpServer(parent)
{
    m_pool = new QThreadPool(this);
    m_pool->setMaxThreadCount(Config::webUiThreads() > 0 ? Config::webUiThreads() : QThread::idealThreadCount());

    if (not listen(QHostAddress(Config::webUiAddress()), Config::webUiPort()))
    {
        qFatal("%s", QString("[WebUI] HTTP server not binded at " + Config::webUiAddress() + ":" + QString::number(Config::webUiPort())).toStdString().c_str());
    }
    qInfo().noquote() << "[WebUI] HTTP server started at" << Config::webUiAddress() + ":" + QString::number( Config::webUiPort() );
    qInfo().noquote() << "[WebUI] HTTP server threads:" << m_pool->maxThreadCount();

    connect (this, &HttpServer::doStopPrivate, this, &HttpServer::stopPrivate, Qt::QueuedConnection);
}

HttpServer::~HttpServer()
{
    qInfo().noquote() << "[WebUI] Stopped";
}

void HttpServer::stop()
{
    emit doStopPrivate();
}

void HttpServer::stopPrivate()
{
    if (QTcpServer::isListening()) QTcpServer::close();

    if (m_pool)
    {
        m_pool->clear();
        if (not m_pool->waitForDone(100))
        {
            qWarning() << "[WebUI] Thread pool not finished in 100 ms";
        }
        m_pool->deleteLater();
        m_pool = nullptr;
    }
}

void HttpServer::incomingConnection(qintptr handle)
{
    HttpServerSocket* socket = new HttpServerSocket(handle);
    socket->setAutoDelete(true);
    m_pool->start(socket);
}
